package com.wwj.auction.common.util;

import com.wwj.auction.common.constant.SystemConstant;
import com.wwj.auction.common.entity.Address;
import com.wwj.auction.common.entity.Cities;
import com.wwj.auction.common.entity.Counties;
import org.springframework.util.ResourceUtils;

import java.io.*;
import java.util.List;
import java.util.Objects;

/**
 * 处理地区信息
 */
public class AddressUtils {

    private static final String FILE_NAME = "classpath:city.json";

    /**
     * 获取地区的原始json数据（未加工的数据）
     * @return
     */
    public static String getOriginalData(){
        return getData(FILE_NAME);
    }

    /**
     * 将地区的json数据处理成前端格式
     *
     * @return
     */
    public static String createRegionData() {
        String json = getData(FILE_NAME);
        // 将provinceCode改为value
        json = json.replaceAll("provinceCode", "value");
        // 将provinceName改为label
        json = json.replaceAll("provinceName", "label");
        // 将cityName改为label
        json = json.replaceAll("cityName", "label");
        // 将cityCode改为value
        json = json.replaceAll("cityCode", "value");
        // 将countyName改为label
        json = json.replaceAll("countyName", "label");
        // 将countyCode改为value
        json = json.replaceAll("countyCode", "value");
        // 将cities改为children
        json = json.replaceAll("cities", "children");
        // 将counties改为children
        json = json.replaceAll("counties", "children");
        // 去除\r\n
        json = json.replaceAll("\n","");
        json = json.replaceAll("\t","");
        json = json.replaceAll("\r","");
        json = json.replaceAll(" ","");
        json = json.replaceAll("\\\\","");
        return json;
    }

    /**
     * 从文件中读取地区信息的json数据
     *
     * @param fileName
     * @return
     */
    private static String getData(String fileName) {
        String json = "";
        try {
            File file = ResourceUtils.getFile(fileName);
            BufferedInputStream in = new BufferedInputStream(new FileInputStream(file));
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            int len = 0;
            byte[] buffer = new byte[1024];
            while ((len = in.read(buffer)) != -1) {
                baos.write(buffer, 0, len);
            }
            json = baos.toString();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return json;
    }
}
